package com.lxm.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.lxm.common.contants.LoginConstants;
import com.lxm.common.contants.RedisExpire;
import com.lxm.common.contants.UserConstants;
import com.lxm.common.tools.JwtUtils;
import com.lxm.dto.Result;
import com.lxm.service.UtilsService;
import com.lxm.vo.LoginVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.impl.DefaultClaims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.lxm.common.contants.UserConstants.JWT_EXPIRE;

@Service
@Slf4j
public class UtilsServiceImpl implements UtilsService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    private JwtUtils jwtUtils;


    @Override
    public Result sendCode(String phone) {
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        //存储验证码
        stringRedisTemplate.opsForValue().set(UserConstants.USER_PHONE + phone, code);
        stringRedisTemplate.expire(UserConstants.USER_PHONE + phone,
                RedisExpire.CODE_EXPIRE, TimeUnit.SECONDS);
        log.debug("验证码：" + code);
        return Result.ok();
    }

    @Override
    public void TWTToken(HttpServletResponse response, LoginVO loginVO) {
        //创造负载体
        Claims claims = new DefaultClaims();
        //放入用户信息
        claims.put(LoginConstants.TOKEN_PREFIX, loginVO);
        //生成token
        String token = jwtUtils.generateToken(claims);
        //存储Token
        stringRedisTemplate.opsForValue().set(UserConstants.USER_TOKEN + loginVO.getUserId(), token);
        stringRedisTemplate.expire(UserConstants.USER_TOKEN + loginVO.getUserId(),
                JWT_EXPIRE, TimeUnit.MINUTES);
        //设置token
        response.setHeader(LoginConstants.TOKEN_HEADER, token);
    }

}
